<template>
  <view class="flex flex-col p-60rpx">
    <view class="h-320rpx flex flex-col justify-end gap-40rpx">
      <view>
        <view class="i-ooui:logo-cc w-80rpx h-80rpx" />
      </view>
      <view class="flex flex-col gap-24rpx tracking-2rpx">
        <text class="font-700 font-size-48rpx text-#383838">Hello!</text>
        <text class="font-700 font-size-48rpx text-#383838">欢迎登录XXX系统</text>
      </view>
    </view>
    <view class="mt-64rpx flex flex-col gap-32rpx w-full">
      <wd-form ref="loginFormRef" custom-class="flex flex-col gap-32rpx" :model="formData">
        <wd-picker
          v-if="tenantInfo.tenantEnabled"
          v-model="formData.tenantId"
          value-key="tenantId"
          label-key="companyName"
          class="rounded-20rpx"
          size="large"
          :columns="tenantInfo.voList"
          label=""
        />
        <wd-input
          v-model="formData.username"
          size="large"
          type="text"
          placeholder="请输入用户名"
          class="rounded-20rpx"
          prop="username"
          :rules="[{ required: true, message: '请填写用户名' }]"
        />
        <wd-input
          v-model="formData.password"
          size="large"
          type="password"
          prop="password"
          placeholder="请输入密码"
          class="rounded-20rpx"
          show-password
          required
          :rules="[{ required: true, message: '请填写密码' }]"
        />
        <wd-input
          v-if="captchaInfo.captchaEnabled"
          v-model="formData.code"
          size="large"
          type="input"
          prop="code"
          placeholder="请输入验证码"
          class="rounded-20rpx"
          use-suffix-slot
          :rules="[{ required: true, message: '请填写验证码' }]"
        >
          <template #suffix>
            <div class="flex h-full justify-center items-center">
              <image
                :src="captchaInfo.img"
                class="w-180rpx h-64rpx rounded-8rpx"
                @click="loadCaptchaImage"
              />
            </div>
          </template>
        </wd-input>
      </wd-form>
      <div class="w-full">
        <wd-button size="large" block :loading="loading" @click="handleSubmit">立即登录</wd-button>
      </div>
    </view>
    <view class="mt-120rpx flex flex-col gap-48rpx">
      <wd-divider>其他登录方式</wd-divider>
      <view class="flex justify-around items-center">
        <image :src="WechatIcon" class="oauth-icon" @click="oauthClick" />
        <image :src="QQIcon" class="oauth-icon" @click="oauthClick" />
        <image :src="WeiboIcon" class="oauth-icon" @click="oauthClick" />
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
  import { onMounted, reactive, ref } from 'vue';
  import type { FormInstance } from 'wot-design-uni/components/wd-form/types';
  import { captchaImage, type CaptchaResponse } from '@/api/auth/captcha';
  import { tenantList } from '@/api/auth';
  import type { LoginParams, TenantResp } from '@/api/auth/model';
  import WechatIcon from '@/assets/wechat.svg';
  import QQIcon from '@/assets/QQ.svg';
  import WeiboIcon from '@/assets/weibo.svg';
  import { useUserStore } from '@/store/modules/user';

  const formData = reactive<{
    tenantId: string;
    username: string;
    password: string;
    code: string;
  }>({
    tenantId: '000000',
    username: 'admin',
    password: 'admin123',
    code: '',
  });

  const captchaInfo = ref<CaptchaResponse>({
    img: '',
    captchaEnabled: false,
    uuid: '',
  });

  async function loadCaptchaImage() {
    const resp = await captchaImage();
    resp.img = `data:image/jpeg;base64,${resp.img}`;
    captchaInfo.value = resp;
  }

  const tenantInfo = ref<TenantResp>({
    voList: [],
    tenantEnabled: false,
  });

  async function loadTenant() {
    const resp = await tenantList();
    tenantInfo.value = resp;
    // 默认选中第一项
    if (resp.voList.length > 0) {
      const tenantId = resp.voList[0].tenantId;
      formData.tenantId = tenantId;
    }
  }

  onMounted(async () => {
    await loadTenant();
    await loadCaptchaImage();
  });

  const loginFormRef = ref<FormInstance>();
  const loading = ref(false);
  const userStore = useUserStore();

  async function handleSubmit() {
    if (!loginFormRef.value) return;
    try {
      loading.value = true;
      /**
       * 校验结果在输入框内显示 不美观
       * 使用reset重置 使用toast来提示错误信息
       */
      const { valid, errors } = await loginFormRef.value.validate();
      loginFormRef.value?.reset();
      if (!valid) {
        const errMsg = errors[0].message;
        uni.showToast({ title: errMsg, icon: 'none' });
        return;
      }
      // 登录
      const loginParams: LoginParams = {
        tenantId: formData.tenantId,
        username: formData.username,
        password: formData.password,
        grantType: 'password',
      };
      // 验证码
      if (captchaInfo.value.captchaEnabled) {
        loginParams.code = formData.code;
        loginParams.uuid = captchaInfo.value.uuid;
      }
      await userStore.login(loginParams);
      await userStore.loadUserInfo(true);
    } catch (e) {
      console.warn(e);
      if (e instanceof Error) {
        const { message } = e;
        // 后端验证码失效/错误并没有返回唯一code 只能这样判断
        if (
          captchaInfo.value.captchaEnabled &&
          (message.includes('验证码') || message.includes('Captcha'))
        ) {
          formData.code = '';
          await loadCaptchaImage();
        }
      }
    } finally {
      loading.value = false;
    }
  }

  function oauthClick() {
    uni.showToast({ title: '自行实现', icon: 'none' });
  }
</script>

<style lang="scss" scoped>
  :deep(.wd-input.is-large) {
    padding: 12rpx 24rpx !important;
    border-radius: 20rpx;
  }

  :deep(.wd-picker__cell) {
    border-radius: 20rpx;
  }

  /**
  去除下部框线
  微信必须加!important才能覆盖
  */
  :deep(.wd-input::after) {
    background: transparent !important;
  }

  .oauth-icon {
    width: 56rpx;
    height: 56rpx;
  }
</style>
